﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;

namespace OnTime
{
    public partial class VisualizerItem : UserControl
    {
        public event EventHandler StopClicked;

        private DateTime _startTime = DateTime.Now;
        private TimeSpan _lastTimespan;

        public VisualizerItem(string projectName)
        {
            InitializeComponent();
            labelTimespan.Text = string.Empty;
            labelName.Text = projectName;
            this.Tag = Guid.NewGuid().ToString();
        }

        public string ProjectName
        {
            get
            {
                return labelName.Text;
            }
        }

        private void UpdateDuration()
        {
            this.BeginInvoke(new Action(() =>
                {
                    var now = DateTime.Now;
                    _lastTimespan = now - _startTime;
                    labelTimespan.Text = string.Format("{0}:{1}:{2}",
                        _lastTimespan.Hours, _lastTimespan.Minutes, _lastTimespan.Seconds);
                }));
        }

        public void ReActivate()
        {
            var now = DateTime.Now;
            _startTime = now - _lastTimespan;

            buttonStop.Enabled = true;
            timerMain.Start();
        }

        // We were told to stop
        public void Stop()
        {
            timerMain.Stop();
            buttonStop.Enabled = false;
        }

        private void buttonStop_Click(object sender, EventArgs e)
        {
            Stop();
            FireStopClicked();
        }

        private void timerMain_Tick(object sender, EventArgs e)
        {
            UpdateDuration();
        }

        private void FireStopClicked()
        {
            if (StopClicked != null)
                StopClicked(this, EventArgs.Empty);
        }
    }
}
